<?php		
	session_start();
	
	header('Content-Type: text/html; charset=UTF-8');

	define( "WB_AKEY" , '2744746528' );
	define( "WB_SKEY" , 'ea56a0ffcd6acb842355b940e0b3071d' );
	define( "WB_CALLBACK_URL" , url("?module=connect&file=sinaweibo&action=callback"));

	/*实例化*/
    include_once( 'includes/saetv2.ex.class.php' );
	$o = new SaeTOAuthV2( WB_AKEY , WB_SKEY );

	switch($action){
	
		
		case 'debug':
			var_dump($_SESSION);
		break;
		
		/*退出*/
		case 'logout':
			
			unset($_SESSION["token"]);
			header("Location: ".url("?module=connect&file=sinaweibo&action=authorize"));
		break;
		
		/*授权*/
		case 'authorize':
			$code_url = $o->getAuthorizeURL( WB_CALLBACK_URL );
			header("Location: $code_url");
		break;
		
		/*返回*/
		case 'callback':
			if (isset($_REQUEST['code'])) {
				$keys = array();
				$keys['code'] = $_REQUEST['code'];
				$keys['redirect_uri'] = WB_CALLBACK_URL;
				try {
					$token = $o->getAccessToken( 'code', $keys ) ;
				} catch (OAuthException $e) {
				}
			}
			
			if ($token) {
				$_SESSION['token'] = $token;
				setcookie( 'weibojs_'.$o->client_id, http_build_query($token) );
				//exit('授权完成');
				
				/*获取信息*/
				$c = new SaeTClientV2( WB_AKEY , WB_SKEY , $_SESSION['token']['access_token'] );
				$ms  = $c->home_timeline(); // done
				$uid_get = $c->get_uid();
				$uid = $uid_get['uid'];
				$user_message = $c->show_user_by_id( $uid);//根据ID获取用户等基本信息，$user_message['screen_name']微薄昵称
				
				
				$memberinfo = $db->get_one("select * from ".DB_PRE."member where `auth_sinaweibo` = '".$token."'");
				if($memberinfo){
					
					$site_auth_key = md5(AUTH_KEY.$_SERVER['HTTP_USER_AGENT']);
					$site_auth = site_auth($userid."\t".$md5_password, 'ENCODE', $site_auth_key);
					set_cookie('auth', $site_auth, $cookietime);
				}
				else{
					$status = $db->insert(DB_PRE.'member',array('auth_sinaweibo'=>$token));
				}


			}
			else{
				exit('授权失败');
			}
		break;
		 
		 
		default:
			$code_url = $o->getAuthorizeURL( WB_CALLBACK_URL );
			
			echo '<a href="<?=$code_url?>">点击进入授权页面</a>';
		break;
	} 
	
	
?>